<template>
  <div class="ipManage">
    <el-tabs v-model="tabIndex" :before-leave="handleTabChange">
      <el-tab-pane label="节点IP池" name="1">
        <el-card class="box-card">
          <p class="text">1、IP使用次数:分配次数按照已经分配给的域名个数计算</p>
          <p class="text">2、删除IP:删除时该IP需要是未分配状态</p>
        </el-card>
        <div class="search-box">
          <el-input class="searchIp" size="mini" v-model="queryParams.slaveIp" clearable placeholder="请输入IP进行模糊查询" />
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        </div>
        <el-table class="table1" v-loading="loading" :data="poolList" v-if="tabIndex == 1">
          <el-table-column label="节点IP" align="center" prop="slaveIp" />
          <el-table-column label="分配次数" align="center" prop="assignNum" />
          <el-table-column label="健康状态" align="center">
            <template slot-scope="scope">
              <template v-if="scope.row.healthStatus == 1">
                <span class="">正常</span>
              </template>
              <template v-else>
                <span class="error">异常</span>
              </template>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize" @pagination="getList" />
        <br />
      </el-tab-pane>
      <el-tab-pane label="新增IP" name="2">
        <div class="addIp">
          <el-input class="searchIp" size="mini" v-model="addIpInfo.ipStr" clearable placeholder="请输入IP进行模糊查询">
            <template slot="prepend">location:</template>
            <el-button slot="append" icon="el-icon-search" @click="toSearchIp"></el-button>
          </el-input>
          <div style="padding:5px 0 0 5px">
            <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll"
              @change="handleCheckAllChange">全选</el-checkbox> {{ numTrue }}
          </div>
          <div class="ip-content">
            <div class="iplist">
              <div class="row" v-for="item in addIpInfo.serviceIpList" :key="item.id">
                <el-checkbox v-model="item.checked" :label="item.id" :disabled="item.exitStatus == 1"
                  @change="handleCheckedCitiesChange">{{ item.ip
                  }}</el-checkbox>
              </div>
            </div>
            <el-button size="mini" type="text" icon="el-icon-right" @click="addIp">添加</el-button>
            <div class="resultList">
              <div class="text" v-for="item in addIpInfo.addIpList" :key="item.id">
                <!-- <span class="ipStr">{{ item.ip }}</span> -->
                <span class="ipStr">{{ item.ip }}</span>
                <i class="el-icon-delete" @click="delIp(item)">删除</i>
              </div>
            </div>
          </div>
          <div class="subBtn">
            <el-button size="mini" type="primary" icon="el-icon-plus" @click="saveAddIp">保存</el-button>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="节点池设置" name="3">
        <el-card class="box-card">
          <p class="text">1、最少分配IP数：节点池给每个域名分配IP的最小数量，如果可用IP不足，则不分配</p>
          <p class="text">2、最多分配IP数：节点池给每个域名分配IP的最大数量；选择不限时，则以最小IP数量分配；其他值则尽可能多的分配资源</p>
          <p class="text">3、IP复用次数：IP能被几个域名共用；不限，可以无限复用；1代表独享，一个IP只能分配给一个域名用；其他值代表有限制的复用</p>
          <p class="text">4、优先分配不同服务器：当分配大于等于2个子IP时，必须是有分属于不同主IP下的IP，避免扎堆到1台服务器</p>
          <p class="text">5、优先最小使用次数IP：满足上述需求外，选择使用次数最小的IP进行分配</p>
        </el-card>
        <el-form ref="form3" :model="poolSetData" :rules="rules" label-width="140px">
          <el-form-item label="最少分配IP数" prop="minNumber">
            <el-select clearable v-model="poolSetData.minNumber" placeholder="请选择最少分配IP数">
              <el-option v-for="i in 100" :value="i" :label="i" />
            </el-select>
            <span>个（默认：2，取值范围：1-100）</span>
          </el-form-item>
          <el-form-item label="最多分配IP数" prop="maxNumber">
            <el-select clearable v-model="poolSetData.maxNumber" placeholder="请选择最多分配IP数">
              <el-option value="0" label="不限" />
              <el-option v-for="i in 100" :value="i" :label="i" />
            </el-select>
            <span>个（默认：不限，取值范围：1-100）</span>
          </el-form-item>
          <el-form-item label="IP复用次数" prop="reuseTimes">
            <el-select clearable v-model="poolSetData.reuseTimes" placeholder="请选择IP复用次数">
              <el-option value="0" label="不限" />
              <el-option v-for="i in 100" :value="i" :label="i" />
            </el-select>
            <span>个（默认：不限，取值范围：1-100）</span>
          </el-form-item>
          <el-form-item label="优先分配不同服务器" prop="allocateDifferentServers">
            <el-select disabled v-model="poolSetData.allocateDifferentServers" placeholder="请选择优先分配不同服务器">
              <el-option :value="0" label="禁止" />
              <el-option :value="1" label="启用" />
            </el-select>
            <span>个（默认：启用，禁止修改）</span>
          </el-form-item>
          <el-form-item label="优先最小使用次数ip" prop="minimumTimesStatus">
            <el-select disabled v-model="poolSetData.minimumTimesStatus" placeholder="请选择优先最小使用次数ip">
              <el-option :value="0" label="禁止" />
              <el-option :value="1" label="启用" />
            </el-select>
            <span>个（默认：启用，禁止修改）</span>
          </el-form-item>
          <el-form-item>
            <div class="subBtn2">
              <el-button type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
            </div>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { listPoolip, delPoolip, seachIpList, addList, addPoolip } from "@/api/system/poolip";
import { getPool, configPoolip } from "@/api/system/pool";
export default {
  name: "IpManage",
  props: {
    id: { type: Number, default: null },
    fromData: {
      type: Object,
      default: {}
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        nodePoolId: '',
        slaveIpId: null,
        slaveIp: null,
        healthStatus: '',
        assignNum: ''
      },
      tabIndex: '1',
      // 总条数
      total: 0,
      // IP智能调度表格数据
      poolList: [],
      addIpInfo: {
        ipStr: '',
        serviceIpList: [],
        addIpList: [],
      },
      poolSetData: {
        id: '',
        minNumber: '2',
        maxNumber: '0',
        reuseTimes: '0',
        allocateDifferentServers: 1,
        minimumTimesStatus: 1,
      },
      // 表单校验
      rules: {},
      checkAll: false,
      isIndeterminate: false,
      numTrue: 0,
    }
  },
  computed: {
  },
  filters: {
  },
  created() {
    this.queryParams.nodePoolId = this.fromData.id;
    this.poolSetData.id = this.fromData.id;
    this.getList();
  },
  methods: {
    handleCheckAllChange(val) {
      // 自定义计算
      // this.checkedCities = val ? cityOptions : [];
      let numTrue = 0
      let numFalse = 0
      this.addIpInfo.serviceIpList.forEach(item => {
        if (item.exitStatus != 1) {
          if (item.checked === true) {
            numTrue++
          } else {
            numFalse++
          }
        }
      })
      this.addIpInfo.serviceIpList = this.addIpInfo.serviceIpList.map(item => {
        if (item.exitStatus != 1) item.checked = numFalse ? true : false
        return item
      })
      this.checkAll = numFalse ? true : false
      this.isIndeterminate = false;// 选一部分是真      
      this.numTrue = numFalse ? numFalse + numTrue : 0
    },
    handleCheckedCitiesChange(value) {
      // 自定义计算
      let numTrue = 0
      let numFalse = 0
      this.addIpInfo.serviceIpList.forEach(item => {
        if (item.exitStatus != 1) {
          if (item.checked === true) {
            numTrue++
          } else {
            numFalse++
          }
        }
      })
      this.checkAll = numFalse == 0 && numTrue > 0 ? true : false
      this.isIndeterminate = !!numFalse && !!numTrue;// 选一部分是真
      this.numTrue = numTrue
    },
    handleTabChange(tabIndex) {
      if (tabIndex == 1) {
        this.getList();
      } else if (tabIndex == 3) {
        this.getPool();
      }
      // return false;
    },
    /** 查询IP智能调度列表 */
    getList() {
      this.loading = true;
      listPoolip(this.queryParams).then(response => {
        this.poolList = response.rows || [];
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handleDelete(item) {
      this.$modal.confirm('是否确认删除节点IP为"' + item.slaveIp + '"的数据项？').then(function () {
        return delPoolip(item.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    toSearchIp() {
      if (this.addIpInfo.ipStr) {
        seachIpList({ ipStr: this.addIpInfo.ipStr, nodePoolId: this.queryParams.nodePoolId }).then(response => {
          let serviceIpList = response.data.serviceIpList || [];
          serviceIpList.forEach(item => {
            item.checked = false;
          });
          this.addIpInfo.serviceIpList = serviceIpList;
          this.numTrue = 0
          this.checkAll = false
          this.isIndeterminate = false
        });
      }
    },
    addIp() {
      console.log(this.addIpInfo.serviceIpList)
      let addIpList = this.addIpInfo.addIpList;
      this.addIpInfo.serviceIpList.forEach(item => {
        if (item.checked) {
          if (this.addIpInfo.addIpList.length) {
            this.addIpInfo.addIpList = this.addIpInfo.addIpList.filter(obj => {
              return item.id != obj.id
            });
          }
          this.addIpInfo.addIpList.push(item)
        }
      });
    },
    delIp(item) {
      this.addIpInfo.addIpList = this.addIpInfo.addIpList.filter(obj => {
        return item.id != obj.id
      });
    },
    saveAddIp() {
      if (this.addIpInfo.addIpList.length) {
        let ids = [];
        this.addIpInfo.addIpList.forEach(item => {
          ids.push(item.id);
        });
        let params = {
          nodePoolId: this.queryParams.nodePoolId,
          slaveIpIdList: ids
        };
        addList(params, { 'Content-Type': 'application/json' }).then(response => {
          this.resetForm2();
          this.$modal.msgSuccess("保存成功");
        });
      } else {
        this.$modal.msg("IP不能为空");
      }
    },
    getPool() {
      getPool(this.poolSetData.id).then(response => {
        this.poolSetData = {
          id: this.poolSetData.id,
          minNumber: response.data.minNumber,
          maxNumber: response.data.maxNumber || '0',
          reuseTimes: response.data.reuseTimes || '0',
          allocateDifferentServers: response.data.allocateDifferentServers,
          minimumTimesStatus: response.data.minimumTimesStatus,
        }
      });
    },
    submitForm() {
      configPoolip(this.poolSetData).then(response => {
        // addPoolip(this.poolSetData).then(response => {
        // this.resetForm3();
        this.$modal.msgSuccess("设置成功");
        this.cancel();
      });
    },
    cancel() {
      // this.resetForm1()
      // this.resetForm2()
      // this.resetForm3()
      this.$emit('handlerIP', false)
    },
    resetForm1() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 6,
        nodePoolId: '',
        slaveIpId: null,
        slaveIp: null,
        healthStatus: '',
        assignNum: ''
      };
      this.poolList = [];
    },
    resetForm2() {
      this.addIpInfo = {
        ipStr: '',
        serviceIpList: [],
        addIpList: [],
      };
    },
    resetForm3() {
      this.poolSetData = {
        id: this.fromData.id,
        minNumber: '2',
        maxNumber: '0',
        reuseTimes: '0',
        allocateDifferentServers: 1,
        minimumTimesStatus: 1,
      }
    },
  }
};
</script>
<style scoped lang="scss">
.search-box {
  display: flex;
  align-items: center;
  justify-content: flex-end;

  .searchIp {
    width: 200px;
  }
}

.table1 {
  .el-table__cell {
    padding: 5px 0;
  }
}

.ip-content {
  width: 100%;
  margin: 10px 0;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .iplist,
  .resultList {
    border: 1px solid #EEEEEE;
    width: 40%;
    padding: 5px;
    height: calc(70vh - 120px);
    overflow-y: auto;

    .text {
      padding: 5px 10px;
      display: flex;
      align-items: center;
      justify-content: space-between;

      &:hover {
        background-color: #f5f5f5;
        cursor: pointer;
      }

      .ipStr {
        margin-right: 20px;
      }
    }
  }
}

.subBtn {
  text-align: center;
}

.subBtn2 {
  text-align: right;
}

.box-card {
  margin-bottom: 10px;

  .el-card__body {
    padding: 8px 10px;

    .text {
      font-size: 12px;
      margin: 5px 0;
    }
  }
}
</style>
